package com.hzit.pay.center.service.strategy.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.hzit.pay.center.exception.BizException;
import com.hzit.pay.center.factory.PayStrategyFactory;
import com.hzit.pay.center.model.PaySerialNoInfo;
import com.hzit.pay.center.service.strategy.IPaymentService;
import com.hzit.pay.center.utils.AlipayUtil;
import com.pay.center.common.enums.PayMethodEnum;
import com.pay.center.common.resp.RespPayData;
import com.pay.center.common.resp.Response;
import com.pay.center.common.utils.PayDigestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 支付宝网页支付
 */
@Service
public class AlipayPagePayServiceImpl implements IPaymentService, InitializingBean {


    private Logger logger = LoggerFactory.getLogger(AlipayPagePayServiceImpl.class);

    @Autowired
    private AlipayUtil alipayUtil;


    @Override
    public Response<RespPayData> payment(PaySerialNoInfo paySerialNoInfo,String respKey) {
        logger.info("#######支付宝网页支付######");

        Response<RespPayData> response = new Response<RespPayData>();

        //调用网页支付的逻辑
        try {
            String payUrl = alipayUtil.alipayPagePayment(paySerialNoInfo);
            if (StringUtils.isEmpty(payUrl)){
                logger.info("订单号：{}，调用支付宝接口失败，原因：支付宝没有返回支付地址",paySerialNoInfo.getOrderId());
                throw new BizException("调用支付宝接口失败");
            }

            response.setCode(0);
            response.setMsg("成功");

            RespPayData payData = new RespPayData();

            payData.setOrderId(paySerialNoInfo.getOrderId());
            payData.setPayUrl(payUrl);
            payData.setPaySerialNo(paySerialNoInfo.getPaySerialNumber());

            JSONObject object = (JSONObject)JSONObject.toJSON(payData);

            String respSign = PayDigestUtil.getSign(object,respKey,"sign");
            payData.setSign(respSign);
            response.setData(payData);

            return response;

        } catch (AlipayApiException e) {
            logger.error("AlipayApiException",e);
            response.setCode(-1);
            response.setMsg(e.getErrMsg());
            return response;
        }





    }

    /**
     * 启动的时候执行
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {

        PayStrategyFactory.concurrentHashMap.put(PayMethodEnum.ALIPAY_TRADE_PAGE_PAY.getCode(),this);

    }
}
